package com.dswfort.novelSpider

import org.jsoup.Jsoup

/**
 * 八一中文网小说解析
 */
class BayizwDownloader : BaseNovelDownloader("https://www.81zw.cm") {

    /**
     * 解析章节清单
     * @param novelUrl 小说地址
     * @return 小说信息
     */
    override fun parseChapters(novelUrl: String): Novel {
        val doc = Jsoup.connect(novelUrl).timeout(30000).get()
        val bookInfoElement = doc.body().select("div[class=book-text]")
        val title = bookInfoElement.select("h1").text()
        val author = bookInfoElement.select("span")[0].text()
        val introduceElement = bookInfoElement.select("div[class=intro]")
        val introduce = introduceElement.text()

        val chapters = ArrayList<Chapter>()
        val chaptersElement = doc.body().select("div[class=book-chapter-list] ul[class=cf]")
        val chapterElements = chaptersElement[1].select("li a")
        for (chapterElement in chapterElements) {
            val chapterUrl = "${host}${chapterElement.attr("href")}"
            val chapter = Chapter(chapterElement.text(), chapterUrl)
            chapters.add(chapter)
        }

        return Novel(title, author, introduce, chapters, novelUrl)
    }

    /**
     * 解析小说章节
     * @param chapter 章节信息
     * @return 章节内容
     */
    override fun parseChapter(chapter: Chapter): String {
        val chapterTitle = chapter.title
        val txt = StringBuilder()
        var pbNext: String
        var pbNextUrl = chapter.url

        do {
            val doc = Jsoup.connect(pbNextUrl).timeout(30000).get()

            val txtElements = doc.body().select("div[class=chapter-box] div[id=txt]").select("p")
            txtElements.forEach {
                if (txt.isNotEmpty()) {
                    txt.append(newline)
                }

                txt.append(it.text())
            }

            // 下一章/下一页
            val pbNextElement = doc.body().select("div[class=chapter-control] a[id=pb_next]")
            pbNext = pbNextElement.text()
            pbNextUrl = "${host}${pbNextElement.attr("href")}"
        } while ("下一页" == pbNext)

        return "${chapterTitle}$newline$txt"
    }
}